import 'package:dio/dio.dart';
import 'package:lyf_shop/hi_net/base_request.dart';
import 'package:lyf_shop/hi_net/hi_error.dart';
import 'package:lyf_shop/hi_net/hi_net_adapter.dart';
import 'package:lyf_shop/hi_net/hi_response.dart';

class DioAdapter extends HiNetAdapter {
  @override
  Future<HiNetResponse<T>> send<T>(BaseRequest request) async {
    // TODO: implement send

    var response, options = Options(headers: request.headers);
    var error;

    try {
      if (request.method() == HTTPMethod.GET) {
        response = await Dio().get(request.url(), options: options);
      } else if (request.method() == HTTPMethod.POST) {
        response = await Dio()
            .post(request.url(), data: request.params, options: options);
      } else if (request.method() == HTTPMethod.DELETE) {
        response = await Dio()
            .delete(request.url(), data: request.params, options: options);
      }
    } on DioError catch (e) {
      error = e;
      response = e.response;
    }

    if (error != null) {
      throw HiNetError(response.statusCode ?? -1, error.toString(),
          data: buildResponse(response, request));
    }

    return buildResponse<T>(response, request);
  }

  HiNetResponse<T> buildResponse<T>(Response res, BaseRequest req) {
    return HiNetResponse(
        data: res.data as T,
        request: req,
        statusCode: res.statusCode,
        statusMessage: res.statusMessage,
        extra: res);
  }
}
